package com.supreme.nettyapp.generalclient.socketclient.handler;

import com.alibaba.fastjson2.JSONObject;
import com.supreme.nettyapp.generalclient.socketclient.entity.FireAlertEntity;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.time.LocalDateTime;
import java.util.Arrays;

public class SocketClientHandler extends SimpleChannelInboundHandler<String> {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("Client channelActive = " + ctx.name());
        ctx.writeAndFlush("Hello Server!\n");
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        try {
            System.out.printf("Received from server: %s %s\n", LocalDateTime.now(), msg);
            JSONObject jsonObject = JSONObject.parseObject(msg);
            String valueString = jsonObject.getString("value");
            FireAlertEntity[] fireAlertEntities = JSONObject.parseObject(valueString, FireAlertEntity[].class);
            System.out.println("fireAlertEntities = " + Arrays.toString(fireAlertEntities));
        } catch (Exception e) {
            System.out.println("jsonObject = " + e.getMessage());
        }
        ctx.writeAndFlush("Client message: " + LocalDateTime.now());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("cause.getMessage() = " + cause.getMessage());
        ctx.close();
    }
}
